package com.item.mobile;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.dialect.PaginationSupport;
import com.base.mobile.MobException;
import com.base.mobile.MobileInfo;
import com.base.mobile.server.annotation.Mobile;
import com.base.mobile.server.annotation.MobileMethod;
import com.base.util.DateUtil;
import com.base.util.StringUtil;
import com.item.dao.model.Diary;
import com.item.dao.model.DiaryExample;
import com.item.dao.model.Essence;
import com.item.dao.model.EssenceExample;
import com.item.dao.model.News;
import com.item.dao.model.NewsExample;
import com.item.dao.model.QuestionExample;
import com.item.dao.model.RecommendMedia;
import com.item.dao.model.RecommendMediaExample;
import com.item.dao.model.SignExample;
import com.item.dao.model.User;
import com.item.service.DiaryService;
import com.item.service.EssenceService;
import com.item.service.NewsService;
import com.item.service.QuestionService;
import com.item.service.RecommendMediaService;
import com.item.service.SignService;
import com.item.service.UserService;
import com.item.util.ConstantResources;
import com.item.util.MyDateUtils;
import com.mobile.api.proto.MAppIndex.MIndex;
import com.mobile.api.proto.MAppIndex.MIndexList;
import com.mobile.api.proto.MAppIndex.MIndexPost;
import com.mobile.api.proto.MAppIndex.MMusic;
import com.mobile.api.proto.MAppNews.MNews;
import com.mobile.api.proto.MAppNews.MNewsList;


@Component
@Mobile
public class MAppIndex {

	@Autowired
	private UserService userService;
	
	@Autowired
	private EssenceService essenceService;
	
	@Autowired
	private DiaryService diaryService;
	
	@Autowired
	private RecommendMediaService recommendService;
	
	@Autowired
	private SignService signService;
	
	@Autowired
	private QuestionService quesService;
	

	static  Logger log = Logger.getLogger(MAppIndex.class);
	
	
	/**
	 * 获取首页
	 * @param mobileInfo
	 * @param date
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MIndex",isLogin=true,isPage=false)
	public MIndexList.Builder index(MobileInfo mobileInfo, String date,Integer type,Integer days) throws Exception {
		return getList(mobileInfo,date,type,days,1);
	}
	
	@MobileMethod(methodno = "MFootprint",isLogin=true,isPage=false)
	public MIndexList.Builder footprint(MobileInfo mobileInfo, String date,Integer type,Integer days) throws Exception {
		return getList(mobileInfo,date,type,days,1);
	}
	
	public MIndexList.Builder getList(MobileInfo mobileInfo, String date,Integer type,Integer days, Integer zj)throws Exception{
		MIndexList.Builder ret = MIndexList.newBuilder();
		//首先获得用户的信息
		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());
		//date为空表示获取今天的
		if(StringUtil.isEmpty(date)){
			date = MyDateUtils.parseDateWithDay(new Date());
		}
		if(type == null){
			type = 0;
		}
		if(type == 1 && days == null){
			days = 10;
		}
		//获取推荐音乐、背景图还有励志语
		RecommendMediaExample rmex = new RecommendMediaExample();
		DiaryExample dex = new DiaryExample();
		rmex.setOrderByClause("date ASC");
		//type等于就是访问10天以后的
		if(type == 0){
			rmex.createCriteria().andDateEqualTo(date);
			dex.createCriteria().andDateEqualTo(date).andUseridEqualTo(mobileInfo.getUserid());
		}else{
			dex.createCriteria().andDateBetween(MyDateUtils.dateStringAdd(date, 0), MyDateUtils.dateStringAdd(date, days-1)).andUseridEqualTo(mobileInfo.getUserid());
			rmex.createCriteria().andDateBetween(MyDateUtils.dateStringAdd(date, 0), MyDateUtils.dateStringAdd(date, days-1));
		}
		List<RecommendMedia> recommends = recommendService.selectByExample(rmex);
		List<Diary> diaries = new ArrayList<Diary>();
		int signDays = 0;
		if(zj == 1){
			diaries = diaryService.selectByExample(dex);
		}
		SignExample sgex = new SignExample();
		//如果发现今天没有添加推荐，那么要报错
		if(recommends == null || recommends.size() < 1){
			rmex.clear();
			rmex.createCriteria().andDateEqualTo("2015-01-28");
			//这一步是确定有的
			recommends = recommendService.selectByExample(rmex);
		}
		QuestionExample qex = new QuestionExample();
		Map<String,String> map = new HashMap<String, String>();
        map.put("userid", mobileInfo.getUserid());
		for(int i = 0 ; i < recommends.size() ; i++){
			MIndex.Builder index = MIndex.newBuilder();
			RecommendMedia rec = recommends.get(i);
			//计算天数
			int day = MyDateUtils.dayDiff(MyDateUtils.parseDateWithDay(user.getCreateTime()), rec.getDate()) + 1;
			index.setDays(day);
			index.setDaysLeft(MyDateUtils.dayDiff(rec.getDate(),ConstantResources.OVERDATE));
			MMusic.Builder music = MMusic.newBuilder();
			music.setTitle(rec.getMusicTitle());
			music.setSinger(rec.getMusicSinger());
			music.setFile(rec.getMusicFile());
			index.addMusic(music);
			index.setContent(StringUtil.emptyIfBlank(rec.getContent()));
			index.setImg(rec.getImg());
			index.setImgZj(rec.getImgZj());
			index.setImgGn(rec.getImgGn2());
			index.setImgGn2(rec.getImgGn3());
			index.setDate(rec.getDate());
			String content = getDiaryContentByDate(diaries, rec.getDate());
			if(StringUtils.isNotBlank(content)){
				index.setDiary(content);
			}
			if(zj == 1){
				sgex.clear();
				sgex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andDateLessThanOrEqualTo(DateUtil.parseDate(rec.getDate(), "yyyy-MM-dd"));
				index.setSignCount(signService.countByExample(sgex));
				sgex.clear();
				sgex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andDateEqualTo(DateUtil.parseDate(rec.getDate(), "yyyy-MM-dd"));
				index.setIsSigned(signService.countByExample(sgex));
			}
			//获取到截止这个日期的复习题目的数量和新增数量
			map.put("date", index.getDate());
			Map<String,Long> result = quesService.getQuestionCount(map);
			index.setAddCount(result.get("todayCount").intValue());
			index.setReviewCount(result.get("reviewCount").intValue());
			ret.addIndex(index);
		}
		return ret;
	}
	
	@MobileMethod(methodno = "MIndexPost",isLogin=true,isPage=false)
	public MIndexPost.Builder indexPost(MobileInfo mobileInfo, String date,Integer type) throws Exception {
		//首先获得用户的信息
		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());
		//date为空表示获取今天的
		if(StringUtil.isEmpty(date)){
			date = MyDateUtils.parseDateWithDay(new Date());
		}
		//计算天数
		int days = MyDateUtils.dayDiff(MyDateUtils.parseDateWithDay(user.getCreateTime()), date) + 1;
		//再获取帖子推荐，最优先推紧急的帖子，没有紧急的帖子则前10天推固定的库里的，之后每天一样推
		MIndexPost.Builder post = MIndexPost.newBuilder();
		EssenceExample eex = new EssenceExample();
		eex.createCriteria().andDateEqualTo(date).andIsUrgentEqualTo(1).andIsDigestEqualTo(0);
		List<Essence> essences = essenceService.selectByExample(eex);
		//表示有临时的紧急推荐
		if(essences != null && essences.size() > 0){
			postDataFit(essences.get(0), post);
		}else{
			//如果超过十天以后，那么就取正常的推荐内容
			if(days > 10){
				eex.clear();
				eex.createCriteria().andDateEqualTo(date).andIsDigestEqualTo(0);
				essences = essenceService.selectByExample(eex);
				if(essences == null || essences.size() < 1){
					throw new MobException(MEnumError.NO_RECOMMEND_ERROR);
				}
				postDataFit(essences.get(0), post);
			}else{
				eex.clear();
				eex.createCriteria().andIsDigestEqualTo(1);
				eex.setOrderByClause("create_time ASC");
				essences = essenceService.selectByExample(eex);
				int total = essences.size();
				postDataFit(essences.get(total / 10 * (days-1) + new Random().nextInt(total / 10)), post);
			}
		}
		return post;
	}
	
	
	public String getDiaryContentByDate(List<Diary> diaries, String date){
		String result = null;
		for(Diary d : diaries){
			if(date.equals(d.getDate())){
				result = d.getContent();
				break;
			}
		}
		
		return result;
	}
	
	public void fillNewsData(News news, MNewsList.Builder ret){
		MNews.Builder newsRet = MNews.newBuilder();
		newsRet.setId(news.getId());
		newsRet.setTitle(news.getTitle());
		newsRet.setDesc(StringUtil.emptyIfBlank(news.getDescription()));
		newsRet.setImg(StringUtil.emptyIfBlank(news.getImg()));
		newsRet.setType(news.getType());
		newsRet.setSource(news.getSource());
		newsRet.setTime(news.getDate());
		if(news.getType() == 1){
			newsRet.setUrl(news.getUrl());
		}else if(news.getType() == 3){
			newsRet.setNoteId(news.getNoteId());
		}
		ret.addNews(newsRet);
	}
	
	public void postDataFit(Essence essence, MIndexPost.Builder post){
		post.setTitle(essence.getTitle());
		post.setId(essence.getId());
		post.setHasDownload(StringUtils.isBlank(essence.getResid()) ? 0 : 1);
		post.setUrl(StringUtil.emptyIfBlank(essence.getUrl()));
	}
}
